import React, { useEffect, useState } from 'react';
import { SecGetList } from '../../../api/index'
import { set_SecList, del_Emp, add_Emp, edit_Emp, del_EmpAll,del_EmpAllStu } from '../../../store/list/index'
import { useAppSelector, useAppDispatch } from '../../../unit/Hooks';
import { Space, Table, Tag, Switch, Button, message, Popconfirm } from 'antd';
import { Segmented, Select, Modal, Typography, Checkbox, Form, Input } from 'antd';
import type { TableProps } from 'antd';
import type { TableColumnsType } from 'antd';
import type { FormProps } from 'antd';
import type { PopconfirmProps } from 'antd';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
// 引用
import Navbar1 from '../../../components/navbar1/navbar1';
import './secur.scss'
import Hoc_login from '../../../unit/Hoc_login';


interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}
function security() {
  //获取数据
  const dispatch = useAppDispatch()
  useEffect(() => {
    (
      async () => {
        let res = await SecGetList()
        // console.log('安防管理', res.data.data.result[0].list);
        dispatch(set_SecList(res.data.data.result[0].list))
      }
    )()
  }, [])
  const secBox = useAppSelector(state => {
    return state.list.data
  })
  // console.log('secBox', secBox);
  // 删除
  const confirm = (key: string) => {
    // console.log(key);
    dispatch(del_Emp(key))
    message.success('确定删除');
  };
  // 批量删除
  const allDel = () => {
    dispatch(del_EmpAllStu(selectedRowKeys)); //批量删除派发
    selectedRowKeys.length = 0;
  }
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    // console.log(e);
    message.error('确定退出');
  };

  //新增 编辑
  //Model对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [title, setTitle] = useState('')
  const [key, setKey] = useState('')
  const [form] = Form.useForm();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //增加 
  const add = () => {
    showModal()
    setTitle('新增')
    form.resetFields();
  }

  // 编辑
  {/* stuNo  stuName  image bourn switch expertiseName  */ }

  const edit = (values: any) => {
    showModal()
    setTitle('编辑')
    setKey(values.key)
    form.setFieldsValue({
      stuName: values.stuName,
      stuNo: values.stuNo,
      bourn: values.bourn,
      switch: values.switch,
      expertiseName: values.expertiseName,
      // img:'https://ts1.cn.mm.bing.net/th/id/R-C.a61fe623e21888f41c57a9202109807f?rik=uvP1YDOjUyv7%2fw&riu=http%3a%2f%2fwww.dgqfdq.com%2fuploads%2fallimg%2f210201%2f2-210201102034a3.jpg&ehk=ViF5bFM%2bDOMY08xA7en%2fpDmEleWEqW5JUa04yf2cnoo%3d&risl=&pid=ImgRaw&r=0'
    });
  }

  // 增加 编辑共用表单
  type FieldType = {
    key: string;
    createdTime?: string;
    stuName?: string;
    address?: string;
    stuNo?: string;
    className?: string;
    salary?: string;
    workCity?: string;
    expertiseName?: string;
    origin?: string;
    collegeName?: string;
    gradYear?: string;
    image?: string;
    bourn?: string;
    switch?: boolean;
  };

  const onFinish = (values: FieldType) => {
    if (title === '新增') {
      values.key = new Date().toLocaleString()
      dispatch(add_Emp(values))
    } else {
      values.key = key
      dispatch(edit_Emp(values))
    }
    // console.log('Success:', values);
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    // console.log('Failed:', errorInfo);
  };

  //搜索
  const [filtedTable, setfiltedTable] = useState([])
  const goSearchs = (value: any) => {
    // console.log(value, '222');
    const filterData = secBox.filter((item: any) => {
      return (
        (value.stuName ? item.stuName.includes(value.stuName) : true)
        && (value.bourn ? item.bourn.includes(value.bourn) : true)
        && (value.expertiseName ? item.expertiseName.includes(value.expertiseName) : true)
      )
    })
    setfiltedTable(filterData)
    // console.log('搜索后数据', filterData);

  }
  useEffect(() => {
    setfiltedTable(secBox)
  }, [secBox])


  const columns: TableColumnsType<DataType> = [
    {
      title: 'ID',
      dataIndex: 'stuNo',
      key: 'stuNo',
    },
    {
      title: '值班人员',
      dataIndex: 'stuName',
      key: 'stuName',
    },
    {
      title: '监控实时图',
      dataIndex: 'image',
      key: 'image',
      render: (title) => <img style={{ width: '70px', height: '50px' }} src={title} alt="" />,
    },
    {
      title: '监控分布位置',
      dataIndex: 'bourn',
      key: 'bourn',
    },
    {
      title: '门禁状态',
      dataIndex: 'switch',
      key: 'switch',
      render: (title) => {
        if (title == 1) {
          return <Switch checkedChildren='打开' unCheckedChildren={title} defaultChecked />
        } else {
          return <Switch checkedChildren='打不开' unCheckedChildren={title} />
        }
      }
    },
    {
      title: '班级人数',
      dataIndex: 'expertiseName',
      key: 'expertiseName',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => edit(record)}>查看</a>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(record.stuNo)}
            onCancel={() => cancel}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>

          <a onClick={() => edit(record)}>编辑</a>
        </Space>
      ),
    },
  ];
  // 选中
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  return (
    <div className="securBox">
      <div className="top">
        <Navbar1 goSearch={goSearchs}></Navbar1>
      </div>
      <div className="foot">
        <Button className='btn' type="primary" onClick={add}>新增毕业学生</Button>
        {/* 新增 model对话框 */}
        <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <Form
            form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >

            {/* stuNo  stuName  image bourn switch expertiseName  */}
            {/*   ID  值班人员 监控实时图 监控分布位置 门禁状态 班级人数  */}
            <Form.Item<FieldType>
              label="ID"
              name="stuNo"
              rules={[{ required: true, message: 'Please input your stuNo!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="值班人员"
              name="stuName"
              rules={[{ required: true, message: 'Please input your stuName!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="监控分布位置"
              name="bourn"
              rules={[{ required: true, message: 'Please input your bourn!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="门禁状态"
              name="switch"
              rules={[{ required: true, message: 'Please input your switch!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="班级人数"
              name="expertiseName"
              rules={[{ required: true, message: 'Please input your expertiseName!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        <Button className='btn' type="primary" onClick={allDel}>批量删除</Button>
        <Table rowSelection={rowSelection} columns={columns} dataSource={filtedTable} rowKey={(record) => record.stuNo} />
      </div>
    </div>
  )
}

export default Hoc_login(security)
